import { Node } from '../engine/core/node.js';
import { databus } from './databus.js';
import { Enemy } from './enemy.js';

export class EnemyManager extends Node {
    constructor() {
        super();

        this.enemyCooldown = databus.enemyCooldown;
        this._time = 0;
        this._enemies = [];
    }

    onUpdate(timestamp, frameDelta) {
        this._time += frameDelta;

        if (this._time > this.enemyCooldown) {
            this._time %= this.enemyCooldown;

            if (this.parent != null) {
                let enemy = null;
                let x = rnd(-0.4, 0.4);
                let y = 1.1;
                let z = 0.0;

                if (this._enemies.length > 0) {
                    enemy = this._enemies.shift();
                    enemy.reset(x, y, z);
                }
                else {
                    enemy = new Enemy(x, y, z);

                    let that = this;

                    enemy.addEventListener("recover", function () {
                        that._enemies.push(this);
                    });
                    this.add(enemy);
                }
            }
        }
    }
}

function rnd(start, end) {
    return Math.random() * (end - start) + start;
}